/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import merlion.common.session.stateless.FileManagerSessionLocal;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 *
 * @author Zhang Ying
 */
public class ExportReportToPdf extends HttpServlet {

    @Resource(name = "merlionDataSource")
    private DataSource merlionDataSource;
    @EJB
    private FileManagerSessionLocal fileSession;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // picture id from request
        String reportType = request.getParameter("type");
        String strId = request.getParameter("strId");
        System.out.println("laha hahahah "+ reportType + " "+ strId);
        if (reportType == null || strId == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            System.out.println("report id is nulll or strId is nulll");
            return;
        }

        // check which type of the report it is
        String reportPath = "";
        HashMap parameters = new HashMap();
        // Test report path
        String path = request.getSession(true).getServletContext().getRealPath("/jasperreports");
        path = path.replace("\\", "\\\\") + "\\\\";
        parameters.put("SUBREPORT_DIR", path);
        
        if (reportType.equals("salesQuotation")) {
            reportPath = "/jasperreports/salesquotation.jasper";
            parameters.put("sqnumber", fileSession.getSalesQuotationById(Long.valueOf(strId)).getSqNumber());
        } else if (reportType.equals("salesOrder")) {
            reportPath = "/jasperreports/salesorder.jasper";
            parameters.put("soidstr",fileSession.getSalesOrderById(Long.valueOf(strId)).getSalesOrderIdStr());
        } else if (reportType.equals("invoice")) {
            reportPath = "/jasperreports/invoice.jasper";
            parameters.put("invoicenumber", fileSession.getInvoiceById(Long.valueOf(strId)).getInvoiceId());
            System.out.println(reportPath + "  " +fileSession.getInvoiceById(Long.valueOf(strId)).getInvoiceId());
        } else if (reportType.equals("receipt")) {
            reportPath = "/jasperreports/receipt.jasper";
            parameters.put("receiptnumber", fileSession.getReceiptById(Long.valueOf(strId)).getReceiptId());
        } else if (reportType.equals("rawMaterialPurchaseOrder")) {
            reportPath = "/jasperreports/raw_material_PO.jasper";
            parameters.put("rawmaterialpo", fileSession.getRawMaterialPurchaseOrderById(Long.valueOf(strId)).getPoNum());
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            System.out.println("report type not exists");
            return;
        }

        // set response type
        response.setContentType("application/pdf");

        // streams
        InputStream reportStream = request.getServletContext().getResourceAsStream(reportPath);
        ServletOutputStream output = null;

        try {
            // open streams
            byte[] pdf = JasperRunManager.runReportToPdf(reportStream, parameters, merlionDataSource.getConnection());
            output = response.getOutputStream();

            // write image contents into reponse
            output.write(pdf);
            output.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("haha, i have exceptions for exporttopdf servlet");
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
